package com.etl.es.charts.base;

import com.eksframework.commons.core.base.EksAsserter;
import com.eksframework.commons.core.base.EksCheck;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class ChartBuilder {

    private List<String> columns;
    private List<List<Object>> values;

    private ChartBuilder() {
    }

    public static ChartBuilder of() {
        return new ChartBuilder();
    }

    public static ChartBuilder of(List<String> columnList) {
        ChartBuilder builder = new ChartBuilder();
        builder.buildColumns(columnList);
        return builder;
    }

    public static ChartBuilder of(String... cols) {
        ChartBuilder builder = new ChartBuilder();
        builder.buildColumns(cols);
        return builder;
    }

    public ChartBuilder buildColumns(List<String> columnList) {
        this.columns = columnList;
        return this;
    }

    public ChartBuilder buildColumns(String... cols) {
        this.columns = Arrays.asList(cols);
        return this;
    }

    public ChartBuilder buildValues(String... cols) {
        this.columns = Arrays.asList(cols);
        return this;
    }

    public ChartBuilder addValues(Object... vals) {
        EksAsserter.notEmpty(vals);
        return this.addValues(Arrays.asList(vals));
    }

    public ChartBuilder addValues(List<Object> valueList) {
        EksAsserter.notEmpty(valueList);
        if (EksCheck.isNull(values)) {
            values = Lists.newArrayList();
        }
        values.add(valueList);
        return this;
    }

    public ChartResult toChartsResult() {
        ChartResult result = ChartResult.builder().build();
        if (EksCheck.isEmpty(this.columns)) {
            return result;
        }
        result.setColumns(this.columns);
        if (EksCheck.isEmpty(this.values)) {
            return result;
        }
        List<Map<String, Object>> rows = Lists.newArrayList();
        for (List<Object> list : values) {
            EksAsserter.isTrue(this.columns.size() == list.size(),
                    "The columns length not equals the values length");
            Map<String, Object> map = Maps.newHashMap();
            for (int i = 0; i < list.size(); i++) {
                map.put(this.columns.get(i), list.get(i));
            }
            rows.add(map);
        }
        result.setRows(rows);
        return result;
    }
}
